<?php
/*
 * 码云webhooks自动更新程序
 * 根据不同分支来自动更新正式站/测试站
 * $logdir 日志存放目录
 * $name 站点标识字符，多站点方便区分日志
 * $password 码云设置的访问密码
 * $wwwroot 正式站点目录
 * $testdir 测试站点目录
 * author： 王小滔
 * date： 2019-11-23
 */

$logdir = "/www/wwwroot/webhook/logs/";
$name = 'harmony_cms';
$password = 'Harmony.2020';
$wwwroot = '/www/wwwroot/harmony_cms';
$testdir = '/www/wwwroot/harmony_cms_test';

$json = file_get_contents("php://input");
$data = json_decode($json, true);
if ($data['password'] != $password) {
    die('Password id error!');
}
if (isset($data['ref']) && $data['total_commits_count'] > 0) {
    if ($data['ref'] == 'refs/heads/master') {
        $dir = $wwwroot;
        $branch = 'master';
        $site = '正式';
    } else {
        $dir = $testdir;
        $branch = 'develop';
        $site = '测试';
    }
    $res = PHP_EOL . "pull start ---------------------------------------------" . PHP_EOL;
    $res .= shell_exec("cd {$dir} && git pull origin {$branch} 2<&1 ");
    $res_log = '------------------------------------------------------------' . PHP_EOL;
    $res_log .= $site . '站点更新，目录：' . $dir . PHP_EOL;
    $res_log .= $data['user_name'] . ' 在 ' . date('Y-m-d H:i:s') . ' 向 ' . $data['repository']['name'] . ' 项目的 ' . $data['ref'] . ' 分支push了 ' . $data['total_commits_count'] . ' 个commit：' . $data['commits']['message'];
    $res_log .= $res . PHP_EOL;
    $res_log .= "pull end -----------------------------------------------------" . PHP_EOL;
    file_put_contents($logdir . $name . "_" . date('Ymd') . ".txt", $res_log, FILE_APPEND);
}